package memberships;

import java.util.List;

import utils.Point;

public abstract class MembershipFunction {
	
	/**
	 * List of points from which shape of membership function is created.
	 */
	protected List<Point> points;
	
	public enum Type {
		TRIANGULAR, TRAPEZOIDAL;
	}
	
	/**
	 * Compute value of the membership function.
	 * @author Adam Taciak
	 * @param x description
	 * @return description
	 */
	public double y(double x) {
		Point firstPnt = points.get(0);
		Point lastPnt = points.get(points.size() - 1);
		
		int pointsInterval = 0;
		double retValue;
		
		if (x <= firstPnt.x) {
			//System.out.println("x is less than first point");
			return firstPnt.y;			// x is less than first point
		} else if (x >= lastPnt.x) {
			//System.out.println("x is bigger than last point");
			return lastPnt.y;			// x is bigger then last point
		} else {
			// Find interval where point x is among
			for (int i = 0; i < points.size() - 1; ++i) {
				if (x > points.get(i).x && x < points.get(i+1).x) {
					pointsInterval = i;
					//System.out.println("x is between " + points.get(i).x + " and " + points.get(i+1).x);
					break;
				}
			}
			retValue = valueFromLinearFunction(x, points.get(pointsInterval), points.get(pointsInterval+1));
		}
		
		return retValue;
	}
	
	/**
	 * 
	 * @param x Position between points A and B
	 * @param A	Point A
	 * @param B Point B
	 * @return
	 */
	private double valueFromLinearFunction(double x, Point A, Point B) {
		// Compute a
		double result = A.y - B.y;
		double a = A.x - B.x;
		
		result = result / a;
		a = a / a;
		a = result;
		
		// Compute b
		result = A.y;
		double b = A.x * a;
		b = result - b;
		
		return a*x+b;
	}
}
